package nio.zero_copy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIOCopyClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        if (!socketChannel.connect(new InetSocketAddress("localhost", 9002))) {
            while (!socketChannel.finishConnect()) {
                System.out.println("连接中...");
            }
        }
        String fileName = "D:\\java-ee\\java-ee\\netty\\src\\main\\java\\nio\\zero_copy\\protoc-22.1-win64.zip";
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        // 发送数据
        long startTime = System.currentTimeMillis();
        /**
         * 在 Linux 下, 一个 transferTo 方法可以完成传输
         * 在 Windows 下, 调用 transferTo 只能发送 8M 数据，因此需要分段传输
         * 8 * 1024 * 1024
         */
        long block = 8 * 1024 * 1024;
        long count = (fileChannel.size() / block);
        long transferCount = 0L;
        for (int i = 0; i < count; i++) {
            transferCount += fileChannel.transferTo(count, block, socketChannel);
        }
        if (fileChannel.size() % block != 0) {
            transferCount += fileChannel.transferTo(count, (fileChannel.size() % block), socketChannel);
        }
        System.out.println("发送总字节数: " + transferCount + "耗时：" + (System.currentTimeMillis() - startTime));
        fileChannel.close();
    }
}
